package com.robotserver.orders.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.entity.VipOrders;
import com.robotserver.orders.entity.VipTokens;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.mapper.VipOrdersMapper;
import com.robotserver.orders.mapper.VipTokensMapper;
import com.robotserver.orders.param.VipOrderSyncParam;
import com.robotserver.orders.service.VipRefundOrderService;
import com.robotserver.orders.service.VipRefundOrderSyncService;
import com.robotserver.orders.vo.VipOrderTimeVO;
import com.vip.adp.api.open.service.*;
import com.vip.osp.sdk.context.InvocationContext;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2020/12/2 18:03
 * @Description:
 */
@Service
public class VipRefundOrderSyncServiceImpl implements VipRefundOrderSyncService {
    private static Logger logger = LoggerFactory.getLogger(VipOrderSyncServiceImpl.class);

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private VipTokensMapper vipTokensMapper;
    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private VipOrdersMapper vipOrdersMapper;

    @Value("${vip.service.url}")
    private String vipServiceUrl;

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder(List<VipOrderTimeVO> vipOrderTimeVOS, List<VipTokens> vipTokens, String lockName) {
        threadLockSyncOrder(vipOrderTimeVOS,vipTokens,lockName);
    }

    @Override
    public void threadLockSyncOrder(List<VipOrderTimeVO> vipOrderTimeVOS, List<VipTokens> vipTokens, String lockName) {
        if (vipTokens.size()>0){
            VipTokens token = null;
            RLock lock = null;
            try {
                lock = redissonClient.getLock(lockName);
                lock.lock();
                token = vipTokens.get(0);
                // 删除对象
                vipTokens.remove(token);
            } catch (Exception e) {
                logger.error("err:{}",e);
            } finally {
                if (lock!=null){
                    lock.unlock();
                }
            }

            if (token!=null){
                logger.info(lockName+"::viptoken>"+token.getOpenId()+"::size:"+vipTokens.size());
                syncOpenUnitOrder(vipOrderTimeVOS,token);
                threadLockSyncOrder(vipOrderTimeVOS,vipTokens,lockName);
            }
        }
    }

    @Override
    public void syncOpenUnitOrder(List<VipOrderTimeVO> vipOrderTimeVOS, VipTokens token) {
        for (VipOrderTimeVO time:vipOrderTimeVOS){
            syncTimeUnitOrder(time,token,1);
        }
    }

    @Override
    public void syncTimeUnitOrder(VipOrderTimeVO time, VipTokens token, int page) {
        try {
            String vip_app_key = sysSettingMapper.getByKey("vip_app_key");
            String vip_app_secret = sysSettingMapper.getByKey("vip_app_secret");

            UnionOrderServiceHelper.UnionOrderServiceClient client = new UnionOrderServiceHelper.UnionOrderServiceClient();
            InvocationContext invocationContext = InvocationContext.Factory.getInstance();
            invocationContext.setAppKey(vip_app_key);
            invocationContext.setAppSecret(vip_app_secret);
            invocationContext.setAppURL(vipServiceUrl);
            invocationContext.setAccessToken(token.getAccessToken());
            invocationContext.setLanguage("zh");
            RefundOrderRequest request = new RefundOrderRequest();
            request.setSearchType(1); //0-维权发起时间，1-维权完成时间（佣金扣除入账时间），2-佣金扣除结算时间
            request.setSearchTimeStart(time.getBeginTime());
            request.setSearchTimeEnd(time.getEndTime());
            request.setPage(page);
            request.setRequestId(IdWorker.getIdStr());
            RefundOrderResponse response = client.refundOrderListWithOauth(request);

            if (response!=null && response.getRefundOrderInfoList()!=null && response.getRefundOrderInfoList().size()>0){
                // 处理订单
                refundOrder(response.getRefundOrderInfoList());
                page = page+1;
                syncTimeUnitOrder(time,token,page);
            }else{
                // 修改心跳
                if (token.getId()!=null){
                    int now = DateUtil.getNowTime();
                    vipTokensMapper.updateHeartbeat(token.getId(),now);
                }
            }
        } catch (Exception e) {
            logger.error("vip sync refund order err:{}",e.getMessage());
        }
    }

    @Override
    public void refundOrder(List<RefundOrderInfo> refundOrderInfoList) {
        for (RefundOrderInfo refundOrderInfo:refundOrderInfoList){
            List<RefundOrderDetail> refundOrderDetails = refundOrderInfo.getRefundOrderDetails();
            for (RefundOrderDetail refundOrderDetail:refundOrderDetails){
                try {
                    logger.info("---VIP Refund Order;orderSn:{},goodsId:{}",new Object[]{refundOrderInfo.getOrderSn(),refundOrderDetail.getGoodsId()});
                    // 根据订单号查询商品是否存在
                    VipOrders vipOrders = vipOrdersMapper.getByOrderSn(refundOrderInfo.getOrderSn(),refundOrderDetail.getGoodsId(),refundOrderDetail.getSizeId());
                    if (vipOrders!=null && vipOrders.getBizStatus().intValue()!=3){
                        VipOrders refundOrder = new VipOrders();
                        refundOrder.setId(vipOrders.getId());
                        if (vipOrders.getBizStatus().intValue() == 1){
                            refundOrder.setBizStatus(3);
                        }else{
                            refundOrder.setBizStatus(2);
                        }
                        refundOrder.setAfterSaleChangeGoodsCount(refundOrderDetail.getGoodsCount());
                        refundOrder.setAfterSaleChangeCommission(refundOrderDetail.getCommission()!=null?Double.parseDouble(refundOrderDetail.getCommission()):0d);
                        refundOrder.setUpdateTime(DateUtil.getNowTime());
                        vipOrdersMapper.update(refundOrder);
                    }
                } catch (Exception e) {
                    logger.error(refundOrderInfo.getOrderSn()+"-"+refundOrderDetail.getGoodsId()+" err:{}",e);
                }
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder_consumer(List<VipOrderTimeVO> vipOrderTimeVOS, VipTokens token) {
        syncOpenUnitOrder(vipOrderTimeVOS,token);
    }

}
